"""
WebSocket高级功能集成
===================

集成所有高级功能到WebSocket服务：
1. 连接池管理
2. 数据压缩和优化
3. 监控告警
4. 数据缓存
5. 权限控制
6. 数据一致性
7. 自动扩缩容
"""

import asyncio
import logging
from typing import Dict, Any, Optional, List
from datetime import datetime
from fastapi import WebSocket

# 导入各个功能模块
from .connection_pool import get_connection_pool, ConnectionPool
from .data_compression import (
    get_data_compressor,
    get_rate_limiter,
    get_update_throttler,
    DataCompressor,
    RateLimiter,
    UpdateThrottler
)
from .websocket_monitor import get_websocket_monitor, WebSocketMonitor
from .websocket_cache import get_websocket_cache, WebSocketDataCache
from .websocket_permission import (
    get_permission_manager,
    get_data_filter,
    get_subscription_validator,
    PermissionManager,
    DataFilter,
    SubscriptionValidator,
    DataCategory
)
from .data_consistency import (
    get_consistency_checker,
    get_data_synchronizer,
    ConsistencyChecker,
    DataSynchronizer,
    DataSource
)
from .websocket_autoscaler import get_autoscaler, AutoScaler

logger = logging.getLogger(__name__)


class AdvancedWebSocketService:
    """
    高级WebSocket服务
    
    集成所有高级功能的WebSocket服务
    """
    
    def __init__(
        self,
        enable_compression: bool = True,
        enable_caching: bool = True,
        enable_monitoring: bool = True,
        enable_permissions: bool = True,
        enable_consistency: bool = True,
        enable_autoscaling: bool = False
    ):
        """
        初始化高级WebSocket服务
        
        Args:
            enable_compression: 启用数据压缩
            enable_caching: 启用数据缓存
            enable_monitoring: 启用监控告警
            enable_permissions: 启用权限控制
            enable_consistency: 启用数据一致性检查
            enable_autoscaling: 启用自动扩缩容
        """
        # 功能开关
        self.enable_compression = enable_compression
        self.enable_caching = enable_caching
        self.enable_monitoring = enable_monitoring
        self.enable_permissions = enable_permissions
        self.enable_consistency = enable_consistency
        self.enable_autoscaling = enable_autoscaling
        
        # 初始化各个组件
        self.connection_pool: ConnectionPool = get_connection_pool()
        
        self.compressor: Optional[DataCompressor] = None
        if enable_compression:
            self.compressor = get_data_compressor()
        
        self.rate_limiter: Optional[RateLimiter] = None
        if enable_compression:
            self.rate_limiter = get_rate_limiter()
        
        self.throttler: Optional[UpdateThrottler] = None
        if enable_compression:
            self.throttler = get_update_throttler()
        
        self.monitor: Optional[WebSocketMonitor] = None
        if enable_monitoring:
            self.monitor = get_websocket_monitor()
        
        self.cache: Optional[WebSocketDataCache] = None
        if enable_caching:
            self.cache = get_websocket_cache()
        
        self.permission_manager: Optional[PermissionManager] = None
        self.data_filter: Optional[DataFilter] = None
        self.subscription_validator: Optional[SubscriptionValidator] = None
        if enable_permissions:
            self.permission_manager = get_permission_manager()
            self.data_filter = get_data_filter()
            self.subscription_validator = get_subscription_validator()
        
        self.consistency_checker: Optional[ConsistencyChecker] = None
        self.data_synchronizer: Optional[DataSynchronizer] = None
        if enable_consistency:
            self.consistency_checker = get_consistency_checker()
            self.data_synchronizer = get_data_synchronizer()
        
        self.autoscaler: Optional[AutoScaler] = None
        if enable_autoscaling:
            self.autoscaler = get_autoscaler()
        
        logger.info(
            f"AdvancedWebSocketService initialized: "
            f"compression={enable_compression}, caching={enable_caching}, "
            f"monitoring={enable_monitoring}, permissions={enable_permissions}, "
            f"consistency={enable_consistency}, autoscaling={enable_autoscaling}"
        )
    
    async def start(self):
        """启动所有后台服务"""
        logger.info("Starting AdvancedWebSocketService...")
        
        # 启动连接池
        await self.connection_pool.start()
        
        # 启动监控
        if self.monitor:
            await self.monitor.start()
        
        # 启动一致性检查
        if self.consistency_checker:
            await self.consistency_checker.start()
        
        # 启动自动扩缩容
        if self.autoscaler:
            await self.autoscaler.start()
        
        logger.info("AdvancedWebSocketService started successfully")
    
    async def stop(self):
        """停止所有后台服务"""
        logger.info("Stopping AdvancedWebSocketService...")
        
        # 停止自动扩缩容
        if self.autoscaler:
            await self.autoscaler.stop()
        
        # 停止一致性检查
        if self.consistency_checker:
            await self.consistency_checker.stop()
        
        # 停止监控
        if self.monitor:
            await self.monitor.stop()
        
        # 停止连接池
        await self.connection_pool.stop()
        
        logger.info("AdvancedWebSocketService stopped")
    
    async def handle_connection(
        self,
        websocket: WebSocket,
        client_id: str,
        user_id: Optional[str] = None
    ) -> bool:
        """
        处理新连接
        
        Args:
            websocket: WebSocket连接
            client_id: 客户端ID
            user_id: 用户ID
        
        Returns:
            是否成功
        """
        # 添加到连接池
        success = await self.connection_pool.add_connection(client_id, websocket)
        
        if success:
            # 记录监控指标
            if self.monitor:
                self.monitor.record_metric("websocket.connection_count", len(self.connection_pool.connections))
            
            logger.info(f"Connection accepted: {client_id}")
        else:
            logger.warning(f"Connection rejected: {client_id}")
        
        return success
    
    async def handle_disconnection(self, client_id: str):
        """
        处理断开连接
        
        Args:
            client_id: 客户端ID
        """
        # 从连接池移除
        await self.connection_pool.remove_connection(client_id)
        
        # 清理订阅
        if self.subscription_validator:
            self.subscription_validator.clear_user_subscriptions(client_id)
        
        # 记录监控指标
        if self.monitor:
            self.monitor.record_metric("websocket.connection_count", len(self.connection_pool.connections))
        
        logger.info(f"Connection closed: {client_id}")
    
    async def handle_subscription(
        self,
        client_id: str,
        user_id: str,
        symbols: List[str],
        category: DataCategory = DataCategory.REALTIME_QUOTE
    ) -> Dict[str, Any]:
        """
        处理订阅请求
        
        Args:
            client_id: 客户端ID
            user_id: 用户ID
            symbols: 股票代码列表
            category: 数据类别
        
        Returns:
            响应消息
        """
        # 验证订阅权限
        if self.subscription_validator:
            is_valid, error_msg = self.subscription_validator.validate_subscription(
                user_id, symbols, category
            )
            
            if not is_valid:
                return {
                    "success": False,
                    "error": error_msg
                }
            
            # 添加订阅
            self.subscription_validator.add_subscriptions(user_id, symbols)
        
        # 记录监控指标
        if self.monitor:
            self.monitor.record_metric("websocket.subscription_count", len(symbols))
        
        return {
            "success": True,
            "subscribed": symbols,
            "category": category.value
        }
    
    async def push_data(
        self,
        client_id: str,
        user_id: str,
        symbol: str,
        data: Dict[str, Any],
        category: DataCategory = DataCategory.REALTIME_QUOTE
    ):
        """
        推送数据给客户端
        
        Args:
            client_id: 客户端ID
            user_id: 用户ID
            symbol: 股票代码
            data: 数据
            category: 数据类别
        """
        # 1. 检查速率限制
        if self.rate_limiter and not self.rate_limiter.allow():
            logger.warning(f"Rate limit exceeded for {client_id}")
            return
        
        # 2. 检查更新频率（节流）
        if self.throttler and not self.throttler.should_update(symbol):
            # 加入待发送队列
            self.throttler.queue_update(symbol, data)
            return
        
        # 3. 过滤数据（权限控制）
        if self.data_filter:
            filtered_data = self.data_filter.filter_market_data(user_id, data, category)
            if filtered_data is None:
                logger.warning(f"Data filtered out for user {user_id}, symbol {symbol}")
                return
            data = filtered_data
        
        # 4. 检查缓存
        if self.cache:
            cached_data = await self.cache.get(f"market:{symbol}")
            if cached_data == data:
                # 数据未变化，不推送
                return
            
            # 更新缓存
            await self.cache.set(f"market:{symbol}", data)
        
        # 5. 数据压缩
        if self.compressor:
            # 创建增量更新
            delta = self.compressor.create_delta(symbol, data)
            if delta:
                data = delta
        
        # 6. 发送数据
        conn_info = self.connection_pool.get_connection(client_id)
        if conn_info:
            try:
                await conn_info.websocket.send_json({
                    "type": "data",
                    "symbol": symbol,
                    "data": data,
                    "timestamp": datetime.now().isoformat()
                })
                
                # 更新活动时间
                self.connection_pool.update_activity(client_id)
                self.connection_pool.increment_message_count(client_id)
                
                # 标记已更新
                if self.throttler:
                    self.throttler.mark_updated(symbol)
                
                # 记录监控指标
                if self.monitor:
                    self.monitor.record_metric("websocket.message_sent", 1)
                
                # 创建一致性检查点
                if self.consistency_checker:
                    self.consistency_checker.create_checkpoint(
                        symbol, data, DataSource.WEBSOCKET
                    )
                
            except Exception as e:
                logger.error(f"Error sending data to {client_id}: {e}")
                self.connection_pool.increment_error_count(client_id)
                
                if self.monitor:
                    self.monitor.record_metric("websocket.error_count", 1)
    
    async def broadcast_data(
        self,
        symbol: str,
        data: Dict[str, Any],
        category: DataCategory = DataCategory.REALTIME_QUOTE
    ):
        """
        广播数据给所有订阅的客户端
        
        Args:
            symbol: 股票代码
            data: 数据
            category: 数据类别
        """
        # 获取所有订阅该symbol的用户
        if self.subscription_validator:
            # 这里简化实现，实际需要维护订阅关系
            # TODO: 实现订阅关系管理
            pass
        
        # 广播给所有连接
        for client_id, conn_info in self.connection_pool.connections.items():
            user_id = client_id  # 简化处理
            await self.push_data(client_id, user_id, symbol, data, category)
    
    def get_comprehensive_stats(self) -> Dict[str, Any]:
        """获取综合统计信息"""
        stats = {
            "timestamp": datetime.now().isoformat(),
            "connection_pool": self.connection_pool.get_statistics()
        }
        
        if self.compressor:
            stats["compression"] = self.compressor.get_stats()
        
        if self.throttler:
            stats["throttler"] = self.throttler.get_stats()
        
        if self.monitor:
            stats["monitor"] = self.monitor.get_health_status()
            stats["active_alerts"] = self.monitor.get_active_alerts()
        
        if self.cache:
            stats["cache"] = asyncio.create_task(self.cache.get_stats())
        
        if self.consistency_checker:
            stats["consistency"] = self.consistency_checker.get_stats()
        
        if self.autoscaler:
            stats["autoscaler"] = self.autoscaler.get_stats()
        
        return stats
    
    def get_health_status(self) -> Dict[str, Any]:
        """获取健康状态"""
        health = {
            "status": "healthy",
            "timestamp": datetime.now().isoformat(),
            "components": {}
        }
        
        # 连接池健康状态
        pool_health = self.connection_pool.get_health_status()
        health["components"]["connection_pool"] = pool_health
        
        # 监控健康状态
        if self.monitor:
            monitor_health = self.monitor.get_health_status()
            health["components"]["monitor"] = monitor_health
            
            # 如果有critical或error级别的告警，标记为不健康
            if monitor_health["status"] in ["critical", "error"]:
                health["status"] = "unhealthy"
        
        return health


# 全局实例
_advanced_service: Optional[AdvancedWebSocketService] = None


def get_advanced_websocket_service(**kwargs) -> AdvancedWebSocketService:
    """获取高级WebSocket服务实例"""
    global _advanced_service
    if _advanced_service is None:
        _advanced_service = AdvancedWebSocketService(**kwargs)
    return _advanced_service

